package com.meiyou.service.impl;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.meiyou.mapper.MeiyouThirMapper;
import com.meiyou.mapper.MeiyouUserMapper;
import com.meiyou.pojo.MeiyouThir;
import com.meiyou.pojo.MeiyouUser;
import com.meiyou.pojo.WXUserInfo;
import com.meiyou.service.TecentService;
import com.meiyou.service.ThirdService;
import com.meiyou.service.WeChatService;
import com.meiyou.utils.Context;
import com.meiyou.utils.Msg;
import com.meiyou.utils.ShareCodeUtil;

import net.sf.json.JSONObject;

@Service
public class WeChatServiceImpl implements WeChatService {

	@Autowired
	MeiyouUserMapper userMapper;
	@Autowired
	TecentService tencentService;
	@Autowired
	ThirdService thirdService;

	public Msg getWxAuthCode(String code, HttpServletRequest req) {
		Msg msg;
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Context.WX_APP_ID + "&secret="
				+ Context.APPSECRET + "&code=" + code + "&grant_type=authorization_code";
		CloseableHttpClient client;
		CloseableHttpResponse response;
		// TODO Auto-generated method stub
		HttpGet get = new HttpGet(url);
		/*
		 * ObjectMapper objectmapper = new ObjectMapper(); Map<String, Object> data =
		 * new HashMap<String, Object>(); data.put("appid", value)
		 */
		client = HttpClients.createDefault();
		try {
			response = client.execute(get);
			HttpEntity repentity = response.getEntity();
			String resresult = EntityUtils.toString(repentity, "utf-8");
			JSONObject json = JSONObject.fromObject(resresult);
			String access_token = json.getString("access_token");// 接口调用凭证
			String openid = json.getString("openid");// 授权用户唯一标识
			/*
			 * msg = Msg.success(); Map<String,Object> map = new HashMap<String,Object>();
			 * map.put("access_token", access_token);
			 */
			/*
			 * msg.setExtend(map); return msg;
			 */
			WXUserInfo wx = getWxUserInfo(access_token, openid);// 获取微信信息

			if (wx == null) {
				return null;
			} else {
				msg = insRegistByWX(wx, req);
				if (msg.getCode() == 100) {
					return msg;
				} else if (msg.getMsg().equals("微信已经绑定了账户")) {
					msg = Msg.success();
					return msg;
				} else {
					return msg;
				}
			}

		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 获取微信用户信息
	 * 
	 * @param access_token
	 * @param openid
	 * @return
	 */
	public WXUserInfo getWxUserInfo(String access_token, String openid) {

		String url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid;
		CloseableHttpClient client;
		CloseableHttpResponse response;
		// TODO Auto-generated method stub
		HttpGet get = new HttpGet(url);
		client = HttpClients.createDefault();
		try {
			response = client.execute(get);
			HttpEntity repentity = response.getEntity();
			String resresult = EntityUtils.toString(repentity, "utf-8");
			JSONObject json = JSONObject.fromObject(resresult);
			WXUserInfo wx = new WXUserInfo();
			wx.setOpenid(json.getString("openid"));
			wx.setNickname(json.getString("nickname"));
			if (json.getInt("sex") == 1) {
				wx.setSex("男");
			} else {
				wx.setSex("女");
			}
			wx.setHeadimgurl(json.getString("headimgurl"));
			return wx;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 通过微信登录自动注册
	 */
	public Msg insRegistByWX(WXUserInfo wx, HttpServletRequest req) {
		System.out.println("获取的用户信息：" + wx.getNickname() + ":" + wx.getSex());
		Msg msg;
		// TODO Auto-generated method stub
		MeiyouThir thir1 = userMapper.getcountByWx(wx.getOpenid());
		if (thir1 == null) {

			
			MeiyouThir thir = new MeiyouThir();
			thir.settWecharcount(wx.getOpenid());
			String ucount = ShareCodeUtil.getRamdomCount();
			thir.settUCount(ucount);
			MeiyouUser user = new MeiyouUser();
			user.setuSex("男");
			user.setuOld(18);
			user.setuCount(ucount);
			user.setuImg(wx.getHeadimgurl());
			user.setuName(wx.getNickname());
			user.setuSex(wx.getSex());
		
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
			user.setuTime(time);
			user.setUmeijin(0);
			if (userMapper.insertSelective(user) == 1) { // 腾讯云通讯账户注册
				if (tencentService.registTencent(user)) {
					if (thirdService.insThirdSelective(thir) == 1) { // 插入第三方支付宝信息和用户信息
						req.getSession().setAttribute("user", user.getuCount());
						msg = Msg.success();
						msg.setCode(500);
						return msg;
					}
				} else {
					msg = Msg.fail();
					msg.setMsg("通讯云IM账户注册失败");
					return msg;
				}
			} else {
				msg = Msg.fail();
				msg.setMsg("服务器异常");
			}
			msg = Msg.fail();
			return msg;

		} else {
			System.out.println("thir不为空");
			System.out.println("微信用户信息：" + thir1.gettUCount() + "," + thir1.gettWecharcount());
			msg = Msg.fail();
			msg.setMsg("微信已经绑定了账户");
			req.getSession().setAttribute("user", thir1.gettUCount());
			return msg;
		}
	}
}
